import axios from 'axios'
import Vue from 'vue'
import Vuex from 'vuex'


Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
    goodsList:[]
    },
    mutations: {
        setGoodsList(state,newList) {
            state.goodsList = newList
        },
    },
    actions: {
        async getList(store) {
            const res = await axios({
                url:'https://www.escook.cn/api/cart'
            })
            store.commit('setGoodsList',res.data.list)
        }
    },
    getters: {
        totalCount(state) {
          return  state.goodsList.reduce((sum, obj) => {
                if (obj.goods_state == true) {
                    sum += obj.goods_count  
                }
                return sum 
            }, 0)
        },
        totalPrice(state) {
            return  state.goodsList.reduce((sum, obj) => {
                  if (obj.goods_state == true) {
                      sum += obj.goods_count *obj.goods_price 
                  }
                  return sum 
              }, 0)
          } 
        
    }
})

export default store